package com.hyjy.music

import com.hyjy.music.bean.Lrc
import com.hyjy.music.util.MUSIC_WHITE_LIST
import java.io.*
import java.nio.charset.StandardCharsets

/**
 * 根据url获取Lrc集合
 *
 * @return Lrc集合
 */
fun String.getLrcList(): List<Lrc> {
    var path = ""
    MUSIC_WHITE_LIST.forEach {
        if (this.endsWith(it)) {
            path = this.replace(it, ".lrc")
        }
    }
    val file = File(path)
    if (!file.exists()) {
        return emptyList()
    }
    var inputStream: InputStream? = null
    val list: MutableList<Lrc> = mutableListOf()
    try {
        inputStream = FileInputStream(file)
        val inputStreamReader = InputStreamReader(inputStream, StandardCharsets.UTF_8)
        val reader = BufferedReader(inputStreamReader)
        var line: String
        // 1.读取每一行歌词
        while (reader.readLine().also { line = it ?: "" } != null) {
            // 2.将歌词解析成bean,放入集合
            // [03:32.43][02:02.72][00:00.31]月半小夜曲
            val array = line.split("]")
            //  [03:32.43   [02:02.72   [00:00.31   月半小夜曲
            var content = array.last().trim() // 最后一个元素是歌词
            if (content.contains("\uE3AC")) {
                content = content.replace("\uE3AC", "")
            }
            // array最后一个元素是歌词,前面的是时间,注意循环的次数是array.size - 1
            for (i in 0 until array.size - 1) {
                if (content.isEmpty()) continue
                list.add(Lrc().apply {
                    this.content = content
                    this.startTime = array[i].formatStartPoint()
                })
            }
        }
        // 3.歌词排序
        list.sort()
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        inputStream.closeSafely()
    }
    return list
}

/**
 * 将[00:22.05格式化为long类型的时间
 */
private fun String.formatStartPoint(): Long {
    return runCatching {
        val result = replace("[", "") // 得到00:22.05
        val index1 = result.indexOf(":")
        val minute = result.substring(0, index1).toInt() // 得到多分钟
        val index2 = result.indexOf(".")
        val second = result.substring(index1 + 1, index2).toInt() // 得到多少秒
        val mills = result.substring(index2 + 1) // 毫秒数字符串形式
        val coefficient: Long = when (mills.length) {
            // 毫秒数可能是两位数,也可能是三位数
            2 -> {
                10L // [01:46.54]让我们红尘作伴活得潇潇洒洒
            }
            3 -> {
                1L // [01:46.540]让我们红尘作伴活得潇潇洒洒
            }
            else -> {
                0L
            }
        }
        minute * 60L * 1000L + second * 1000L + mills.toInt() * coefficient
    }.onFailure {
        it.printStackTrace()
    }.getOrDefault(0L)
}

fun Closeable?.closeSafely() {
    try {
        this?.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}